import app from '../utils/cloudbase';

// 确保登录状态的函数
async function ensureLogin() {
  const auth = app.auth();
  if (!auth.hasLoginState()) {
    await auth.signInAnonymously();
  }
}

//分页查询
export function page(params) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      app.callFunction({
        name: 'Book',
        data: {
          action: 'getShops',
          page: params.pageNum,
          pageSize: params.pageSize
        }
      }).then(res => {
        resolve({ data: res.result });
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

//查询旗下商店
export function selectShop() {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      app.callFunction({
        name: 'Book',
        data: {
          action: 'getShops'
        }
      }).then(res => {
        if (res.result.code === 200) {
          resolve({ 
            data: res.result.data.map(shop => ({
              id: shop._id,
              shopName: shop.name
            })),
            statusCode: "200"
          });
        } else {
          reject(new Error(res.result.message || '获取商店列表失败'));
        }
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

//保存商店
export function save(params) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      app.callFunction({
        name: 'Book',
        data: {
          action: params.id ? 'updateShop' : 'addShop',
          shop: {
            name: params.shopName,
            address: params.address,
            phone: params.phone,
            description: params.description
          }
        }
      }).then(res => {
        resolve({ data: res.result });
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

//删除商店
export function deleteByIds(data) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      app.callFunction({
        name: 'Book',
        data: {
          action: 'deleteShop',
        }
      }).then(res => {
        resolve({ data: res.result });
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

